package net.huashitong.oversee.web;

import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.Project.entity.MessageList;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.filter.MessageListFilter;
import net.huashitong.Project.service.MessageListService;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.nodeFile.entity.SysBnpFile;
import net.huashitong.nodeFile.service.SysBnpFileService;
import net.huashitong.oversee.entity.GradePoint;
import net.huashitong.oversee.entity.ScoreSummary;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.CoordinateFilter;
import net.huashitong.oversee.filter.GradePointFilter;
import net.huashitong.oversee.filter.ScoreSummaryFilter;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.CoordinateService;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.ScoreSummaryService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.taskGroup.entity.JobGroup;
import net.huashitong.taskGroup.service.JobGroupService;
import net.huashitong.user.databean.BnpUserDatabean;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.zhApp.service.AppGradePointService;
import org.quartz.Job;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 绩点考核
 */
@Controller
@RequestMapping("/gradepoint")
public class GradePointCtrl extends JsonBaseController {

    @Autowired
    private GradePointService gradePointService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private SupervisionTaskService supervisionTaskService;
    @Autowired
    private CoordinateService coordinateService;
    @Autowired
    private JobGroupService jobGroupService;
    @Autowired
    private ScoreSummaryService scoreSummaryService;
    @Autowired
    private SysBnpFileService fileservice;
    @Autowired
    private AppGradePointService appGradePointService;
//    @Autowired
//    private MessageListService messageListService;

    @Override
    protected String getView(String s) {
        return "/modules/gradepoint/" + s;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
        model.addAttribute("leftType", "绩效考核");
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (ObjectUtils.isBlank(bnpUser)) {
            return "/modules/login/login";
        }
        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
        model.addAttribute("myTaskNum", myTaskNum);
        model.addAttribute("quetionNum", quetionNum);

        int myTackTaskNum = (int) WebUtils.getSessionAttribute(request, "myTackTaskNum");
        model.addAttribute("myTackTaskNum", myTackTaskNum);

        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
        model.addAttribute("nodeCount", nodeCount);

        model.addAttribute("user", bnpUser);
        return getView("query");
    }

    /**
     * 初始化数据
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute GradePointFilter filter, HttpServletRequest request) {

        List<JobGroup> jobGroups = jobGroupService.query();
        Map<String, String> jobGroupMap = new HashMap<>();
        for (JobGroup j : jobGroups) {
            if (!jobGroupMap.containsKey(j.getGroupTel())) {
                jobGroupMap.put(j.getGroupTel(), j.getGroupCode());
            }
        }
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (!"2".equals(bnpUser.getBranchType()) && !"4".equals(bnpUser.getBranchType())) {
            filter.setCheckObjectId(bnpUser.getSysId());
        }
        //督查组
        if ("4".equals(bnpUser.getBranchType())) {
            if (StringUtils.isNotBlank(jobGroupMap.get(bnpUser.getPhone()))) {
                filter.setCheckObjectId(jobGroupMap.get(bnpUser.getPhone()));
            }
        }

        if (StringUtils.isNotBlank(filter.getCheckType())) {
            if (filter.getPaging().getCurrentPage() == 1) {
                List<GradePoint> allList = gradePointService.queryGradePointByCheckType(filter.getCheckType());
                Collections.sort(allList, new Comparator<GradePoint>() {
                    @Override
                    public int compare(GradePoint g1, GradePoint g2) {
                        double score1 = Double.parseDouble(StringUtils.isBlank(g1.getSoucre()) ? "0" : g1.getSoucre());
                        double score2 = Double.parseDouble(StringUtils.isBlank(g2.getSoucre()) ? "0" : g2.getSoucre());
                        if (score1 < score2) {
                            return 1;
                        } else if (score1 == score2) {
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                });
                for (int i = 0, s = allList.size(); i < s; i++) {
                    if (i > 0 && Double.parseDouble(StringUtils.isBlank(allList.get(i).getSoucre()) ? "0" : allList.get(i).getSoucre())
                            == Double.parseDouble(StringUtils.isBlank(allList.get(i - 1).getSoucre()) ? "0" : allList.get(i - 1).getSoucre())) {
                        allList.get(i).setTypeRank(allList.get(i - 1).getTypeRank());
                    } else {
                        allList.get(i).setTypeRank(i + 1 + "");
                    }
                }
                gradePointService.batchUpdate(allList);
            }
            List<GradePoint> lists = gradePointService.queryGradePoint(filter);
            for (GradePoint gradePoint : lists) {
                gradePoint.setRank(gradePoint.getTypeRank());
            }
            return coverJqGrid(filter, lists);
        }
        //==========================================================================================================
        List<GradePoint> lists = gradePointService.queryGradePoint(filter);
        return coverJqGrid(filter, lists);
    }


    /**
     * 查询页面
     *
     * @param filter
     * @return
     */
    @RequestMapping("/filter")
    public String filter(@ModelAttribute GradePointFilter filter) {
        return getView("filter");
    }

    @RequestMapping(value = "/showDetail/{id}", method = RequestMethod.GET)
    public String showEdit(Model model, HttpServletRequest request, @PathVariable String id) {
        GradePoint gradePoint = gradePointService.getById(id);
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        SupervisionTask task = supervisionTaskService.getById(gradePoint.getTaskId());
        if(ObjectUtils.isBlank(task)){
            model.addAttribute("gradePoint", gradePoint);
            return getView("showDetail");
        }

//        //如果用户是督查组，并且督查任务有未读情况，则需要提示
//        if ("4".equals(bnpUser.getBranchType())) {
//            MessageListFilter mf = new MessageListFilter();
//            mf.setUserId(bnpUser.getGroupCode());
//            mf.setTaskId(id);
//            mf.setIsRead("0");
//            List<MessageList> list = messageListService.queryNoReadMessage(mf);
//            if (ObjectUtils.isNotBlank(list)) {
//                //责任单位反馈的消息督查组未读
//                model.addAttribute("resNoRead", "1");
//            }
//        }else{
//            MessageListFilter mf = new MessageListFilter();
//            mf.setUserId(bnpUser.getSysId());
//            mf.setTaskId(id);
//            mf.setIsRead("0");
//            List<MessageList> list = messageListService.queryNoReadMessage(mf);
//            if (ObjectUtils.isNotBlank(list)) {
//                model.addAttribute("superNoRead", "1");
//            }
//        }

        List<JobGroup> jobGroups = jobGroupService.query();
        /**
         * 已经选择的督查组
         */
        if (StringUtils.isNotBlank(task.getGroupType())) {
            String[] grpups = task.getGroupType().toString().split(",");
            List<String> groupsList = Arrays.asList(grpups);
            for (String item2 : groupsList) {
                for (JobGroup item : jobGroups) {
                    if (item.getGroupName().equals(item2)) {
                        item.setGroupDuty("selected");
                    } else {
                        item.setGroupDuty("noSelected");
                    }
                }
            }
        }


        //涉及单位（involveUnit）
        List<BnpUserDatabean> deptLists = coordinateService.queryAllInvolveUnit();
        String involveUnitsStr = task.getInvolveUnit();
        if (StringUtils.isNotBlank(involveUnitsStr)) {
            String[] invArr = involveUnitsStr.split(",");
            List<String> involveUnitsList = Arrays.asList(invArr);
            for (BnpUserDatabean dept : deptLists) {
                boolean flag = false;
                for (String involve : involveUnitsList) {
                    if (involve.equals(dept.getBranch())) {
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    dept.setBranchType("selected");
                } else {
                    dept.setBranchType("noSelected");
                }
            }
        } else {
            for (BnpUserDatabean dept : deptLists) {
                dept.setBranchType("noSelected");
            }
        }
        List<SupervisionTask> list = new ArrayList<>();
        list.add(task);
        list = supervisionTaskService.involveUnitDealWith(list);
        model.addAttribute("jobGroups", jobGroups);
        model.addAttribute("taskjob", list.get(0));
        model.addAttribute("bnpUser", bnpUser);
        model.addAttribute("deptLists", deptLists);
//        return getView("form");
        return getView("detail");
    }

    @RequestMapping("/formHead")
    public String showHead() {
        return getView("formHead");
    }

    @ResponseBody
    @RequestMapping(value = "/getScoreAndRank", method = RequestMethod.GET)
    public Message getScoreAndRank(HttpServletRequest request) {

        List<JobGroup> jobGroups = jobGroupService.query();
        Map<String, String> jobGroupMap = new HashMap<>();
        for (JobGroup j : jobGroups) {
            if (!jobGroupMap.containsKey(j.getGroupTel())) {
                jobGroupMap.put(j.getGroupTel(), j.getGroupCode());
            }
        }
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        Map<String, String> resultMap = appGradePointService.qureyScoreAndRankByBnpUser(jobGroupMap,bnpUser);
        return coverMessage("200", "操作成功", resultMap);
    }


    @RequestMapping(value = "/download/{id}")
    public void downProjectfile(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        downLoadFile(id, req, resp);
    }

    public void downLoadFile(String fileId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        SysBnpFile sysBnpFile = fileservice.getById(fileId);
        if (sysBnpFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysBnpFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        try {
            String fileName = "《绩效考核评分方案》";
            String n = new String(fileName.getBytes(), "iso8859-1");
            resp.setHeader("Content-Type", "application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment; filename=" + n + "." + sysBnpFile.getFileType());
            FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
            return;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }
    }


    /**
     * 统计得分
     * @param filter
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getScoreNumCount", method = RequestMethod.POST)
    public Message getScoreNumCount(@ModelAttribute GradePointFilter filter,HttpServletRequest request) {

        List<JobGroup> jobGroups = jobGroupService.query();
        Map<String, String> jobGroupMap = new HashMap<>();
        for (JobGroup j : jobGroups) {
            if (!jobGroupMap.containsKey(j.getGroupTel())) {
                jobGroupMap.put(j.getGroupTel(), j.getGroupCode());
            }
        }
        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
        if (!"2".equals(bnpUser.getBranchType()) && !"4".equals(bnpUser.getBranchType())) {
            filter.setCheckObjectId(bnpUser.getSysId());
        }
        //督查组
        if ("4".equals(bnpUser.getBranchType())) {
            if (StringUtils.isNotBlank(jobGroupMap.get(bnpUser.getPhone()))) {
                filter.setCheckObjectId(jobGroupMap.get(bnpUser.getPhone()));
            }
        }

        List<Map<String, Object>> map = gradePointService.getScoreNumCount(filter);
        return coverMessage("200", "操作成功", map);
    }
}
